<template>
    <div class="entrustment-management">
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入用户或期刊名称查询" clearable @clear="handleClearSearch"
                class="search-input" />
        </div>

        <el-table :data="entrustments" stripe border>
            <el-table-column prop="user_name" label="申请用户" />
            <el-table-column prop="journal_name" label="期刊名称" />
            <el-table-column prop="from_location" label="当前馆藏地" />
            <el-table-column prop="to_location" label="目标馆藏地" />
            <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                    <el-tag :type="statusTagMap[row.status] || 'info'">
                        {{ statusMap[row.status] || '未知状态' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="created_at" label="申请时间" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="success" @click="handleApprove(row)"
                        :disabled="row.status !== 'pending'">
                        通过
                    </el-button>
                    <el-button size="small" type="danger" @click="handleReject(row)"
                        :disabled="row.status !== 'pending'">
                        拒绝
                    </el-button>
                </template>
            </el-table-column>
        </el-table>


        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="handlePageChange" class="pagination" />
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { entrustmentApi } from '@/request/apiService';
import { ElMessage, ElMessageBox } from 'element-plus';

const entrustments = ref([]);
const search = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 状态映射
const statusMap = {
    pending: '待处理',
    approved: '已通过',
    rejected: '已拒绝',
};

const statusTagMap = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
};

// 获取委托列表
const fetchEntrustments = async () => {
    try {
        const { data, total: totalCount } = await entrustmentApi.getEntrustmentList({
            page: currentPage.value,
            pageSize: pageSize.value,
            search: search.value,
        });
        entrustments.value = data;
        total.value = totalCount;
    } catch (error) {
        console.error('获取委托列表失败', error);
    }
};

// 通过委托
const handleApprove = async (row) => {
    ElMessageBox.confirm('确认通过此委托申请吗？', '提示', {
        confirmButtonText: '通过',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                await entrustmentApi.updateEntrustmentStatus({ entrustment_id: row.entrustment_id, status: 'approved' });
                ElMessage.success('委托申请已通过');
                fetchEntrustments();
            } catch (error) {
                console.error('通过委托失败:', error);
                ElMessage.error('操作失败，请稍后重试');
            }
        })
        .catch(() => console.log('取消操作'));
};

// 拒绝委托
const handleReject = async (row) => {
    ElMessageBox.confirm('确认拒绝此委托申请吗？', '提示', {
        confirmButtonText: '拒绝',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            try {
                await entrustmentApi.updateEntrustmentStatus({ entrustment_id: row.entrustment_id, status: 'rejected' });
                ElMessage.success('委托申请已拒绝');
                fetchEntrustments();
            } catch (error) {
                console.error('拒绝委托失败:', error);
                ElMessage.error('操作失败，请稍后重试');
            }
        })
        .catch(() => console.log('取消操作'));
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    currentPage.value = 1;
    fetchEntrustments();
};

// 分页改变时触发
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchEntrustments();
};

// 页面加载时，获取委托数据
onMounted(fetchEntrustments);

// 监听搜索变化自动获取数据
watch(search, fetchEntrustments);
</script>

<style scoped>
.entrustment-management {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 20px;
}

.pagination {
    margin-top: 20px;
}
</style>
